const azdev = require('azure-devops-node-api');

const token = process.env.TOKEN;
const azureDevOpsRepoId = process.env.REPOSITORY;
const taskName = process.env.TASK_NAME;
const branch = process.env.BRANCH;

const orgUrl = 'https://dev.azure.com/mseng';
const authHandler = azdev.getPersonalAccessTokenHandler(token);

const project = 'AzureDevOps';

const refs = {
  sourceRefName: `refs/heads/${branch}`,
  targetRefName: 'refs/heads/master'
};

const pullRequestToCreate = {
  ...refs,
  title: `Hotfixing tasks: ${taskName.split(',')}`,
  description: 'Autogenerated hotfix PR'
};

const createPullRequest = async () => {
  console.log('Getting connection');
  const connection = new azdev.WebApi(orgUrl, authHandler);

  try {
    console.log('Getting Git API');
    const gitApi = await connection.getGitApi();

    console.log('Checking if an active pull request for the source and target branch already exists');
    let PR = (await gitApi.getPullRequests(azureDevOpsRepoId, refs, project))[0];

    if (PR) {
      console.log('PR already exists');
    } else {
      console.log('PR does not exist; creating PR');
      PR = await gitApi.createPullRequest(pullRequestToCreate, azureDevOpsRepoId, project);
    }

    const prLink = `${orgUrl}/${project}/_git/${azureDevOpsRepoId}/pullrequest/${PR.pullRequestId}`;
    console.log(`Link to the PR: ${prLink}`);
    console.log(`##vso[task.setvariable variable=PR_ID]${PR.pullRequestId}`);
    console.log(`##vso[task.setvariable variable=PR_LINK]${prLink}`);
  } catch (err) {
    console.log('##vso[task.logissue type=error]Failed to open PR');
    console.error(err);
    process.exit(1);
  }
};

createPullRequest();
